<template>
  <div class="app-page">
    <aside-tree
      title="组织机构"
      :tree-data="treeData"
      :loading="$loadingPlugin.getTreeData"
      :mouse-button="false"
      @currentChange="currentChange"
      @refresh="getTreeData"
    />
    <div class="content">
      <el-table-form
        ref="dataForm"
        :model="query"
      >
        <el-form-item
          class="merge-item"
        >
          <el-select v-model="query.csmType" style="width: 170px; margin-right: 2px;">
            <el-option label="电话" value="csmRgPhone" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <el-option label="地址" value="csmRgAddress" />
          </el-select>
          <el-input
            v-model.trim="query.csmText"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="客户等级:"
          prop="unCheckQuality"
        >
          <el-select v-model="query.unCheckQuality" clearable placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="(l, i) in CmsLevelEnum"
              :key="i"
              :label="l.levelName"
              :value="l.levelNum"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="状态:"
          prop="qualityStatus"
        >
          <el-select v-model="query.qualityStatus" clearable placeholder="请选择" style="width: 100%;">
            <el-option label="待审核" :value="1" />
            <el-option label="已审核" :value="2" />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button
            v-permission="7"
            type="primary"
            icon="el-icon-search"
            @click="search"
          >查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;" class="btn-group">
        <div>
          <!-- <el-button type="primary" class="append-search" @click="search">查询</el-button> -->
          <el-button
            v-permission="8"
            type="primary"
            class="append-search"
            @click="edit"
          >编辑</el-button>
          <el-button
            v-permission="7"
            type="primary"
            icon="el-icon-search"
            @click="audit"
          >审核</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        border
        resizable
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        @row-click="toggleSelection"
        @selection-change="handleSelectionChange"
        @fetch="fetchData"
      />
    </div>
    <edit ref="edit" :cms-level-enum="CmsLevelEnum" :fetch-data="fetchData" />
    <CsmDetailModal ref="CsmDetailModal" :type="2" />
    <CsmDetailYaJin
      ref="CsmDetailYaJin"
      :tree-data="treeData"
      :paymen-fil-list="paymenFilList"
      :calc-type-list="calcTypeList"
    />
  </div>
</template>
<script>
  import {
    organizationQueryList,
    queryCustomerLevelEquityPage,
    csmManageQueryList,
    queryCsmTypeMap,
    queryCustomerLevelAudit,
    customerInfo,
    queryMap
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import asideTree from '@/views/components/OrgTree'
  import edit from './edit.vue'
  import CsmDetailModal from '@/views/components/CsmDetailModal'
  import CsmDetailYaJin from '@/views/components/NormalReceiptsAdd'
  export default {
    name: 'gradeAdmin',
    components: {
      asideTree,
      edit,
      CsmDetailModal,
      CsmDetailYaJin
    },
    data() {
      return {
        treeData: [],
        CmsLevelEnum: [], // 客户等级枚举
        currentOrg: null,
        csmTypeEnum: [],
        tableChecklist: [],
        paymenFilList: [],
        calcTypeList: [], // 收款方式
        query: {
          csmType: 'csmRgPhone',

          csmStatus: 9
        },
        tableData: {
          total: 0,
          column: [
            { type: 'index' },
            { type: 'selection' },
            {
              label: '客户编号',
              prop: 'csmCode',
              width: 80,
              align: 'left',
              showOverflowTooltip: true
            },
            {
              label: '客户名称',
              prop: 'csmName',
              width: 120,
              align: 'left',
              showOverflowTooltip: true
            },
            {
              label: '客户类型',
              prop: 'csmType',
              width: 80,
              align: 'left',
              showOverflowTooltip: true,
              render: (h, { row }) => (
              <span>
                {this.csmTypeEnum.find((l) => l.value === row.csmType)
                  ? this.csmTypeEnum.find((l) => l.value === row.csmType).desc
                  : ''}
              </span>
            )
            },
            {
              label: '客户等级',
              prop: 'csmQuality',
              width: 140,
              showOverflowTooltip: true,
              align: 'left',
              // render: (h, { row }) => <span>{ this.CmsLevelEnum.find(l => l.levelNum === row.csmQuality) ? this.CmsLevelEnum.find(l => l.levelNum === row.csmQuality).levelName : '->二级会员' }</span>
              render: (h, { row, column }) => <span>{this.getLevel(row, column)}</span>
            },
            {
              label: '电话',
              prop: 'csmRgPhone',
              width: 120,
              showOverflowTooltip: true,
              align: 'left'
            },
            {
              label: '地址',
              prop: 'csmRgAddress',
              width: '',
              showOverflowTooltip: true,
              align: 'left'
            },
            {
              label: '所属机构',
              prop: 'nearStationName',
              showOverflowTooltip: true,
              width: 160,
              align: 'left'
            },
            {
              label: '状态',
              prop: 'qualityStatus',
              showOverflowTooltip: true,
              width: 80,
              align: 'left',
              render: (h, { row }) => (
              <span>
                {row.qualityStatus === 1
                  ? '待审核'
                  : row.qualityStatus === 2
                  ? '已审核'
                  : ''}
              </span>
            )
            },
            {
              label: '操作',
              align: 'left',
              fixed: 'right',
              width: 210,
              render: (h, { row, $index }) => {
                return (
                <div>
                  <el-link
                    v-permission='10'
                    size='mini'
                    onClick={() => this.binding(row)}
                  >
                    绑定气瓶
                  </el-link>
                  <el-link
                    v-permission='11'
                    size='mini'
                    onClick={() => this.historyDetail(row, $index)}
                  >
                    历史详情
                  </el-link>
                </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    created() {
      this.getTreeData()
      this.queryOptionsMap()
    },
    mounted() {},
    methods: {
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        var query = {
          currentPage,
          pageSize,
          orgSNNo: this.currentOrg ? this.currentOrg.orgSNNo : '',
          ...this.query
        }
        query[this.query.csmType] = this.query.csmText
        delete query.csmText
        delete query.csmType
        if (!this.query.unCheckQuality) query.unCheckQuality = '-1'
        if (!this.query.qualityStatus) query.qualityStatus = '-1'
        if (query.csmRgPhone && query.csmRgPhone.length !== 11) {
          this.$message.error('请输入正确的电话号码')
          return
        }
        const res = await csmManageQueryList(query)
        this.tableData.data = res.data.rows

        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 客户类型枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4] = await Promise.all([
          queryCsmTypeMap(),
          queryMap({ enumName: 'PaymentMethod' }),
          queryCustomerLevelEquityPage({
            keyStatus: -1,
            pageIndex: 0,
            pageSize: 100
          }),
          queryMap({ enumName: 'CalcType' })
        ])
        this.csmTypeEnum = res1.data

        this.CmsLevelEnum = res3.data.rows
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        const _this = this
        res2.data.filter((item) => {
          if (arr.includes(item.desc)) {
            _this.paymenFilList.push(item)
          }
        })

        this.calcTypeList = res4.data // 收款方式
      },
      toggleSelection(row) {
        this.$refs['lbTable'].toggleRowSelection(row)
      },

      // 获取组织机构数据
      async getTreeData() {
        const res = await organizationQueryList({})
        const data = res.data.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择组织机构变化
      currentChange(current) {
        this.fetchData({})
        this.currentOrg = current
        console.log(current)
      },
      getLevel(row, column) {
        var qualityStatus = row.qualityStatus
        // console.log(qualityStatus)
        // this.CmsLevelEnum.find(l => l.levelNum === row.csmQuality).levelName
        if (qualityStatus === 2) {
          // 说明是已审核数据
          var unCheckQuality = row.unCheckQuality
          for (var x = 0; x < this.CmsLevelEnum.length; x++) {
            if (unCheckQuality === this.CmsLevelEnum[x].levelNum) {
              return this.CmsLevelEnum[x].levelName
            }
          }
        } else if (qualityStatus === 1) {
          // 说明是待审核
          var csmQuality = row.csmQuality // 原等级
          unCheckQuality = row.unCheckQuality // 新等级
          var csmQualityValue = ''
          var unCheckQualityValue = ''
          for (x = 0; x < this.CmsLevelEnum.length; x++) {
            // 原等级名称
            if (csmQuality === this.CmsLevelEnum[x].levelNum) {
              csmQualityValue = this.CmsLevelEnum[x].levelName
            }
            // 修改后等级名称
            if (unCheckQuality === this.CmsLevelEnum[x].levelNum) {
              unCheckQualityValue = this.CmsLevelEnum[x].levelName
            }
          }
          return csmQualityValue + '->' + unCheckQualityValue
        }

        return ''
      },
      // table选择
      handleSelectionChange(val) {
        this.tableChecklist = val
      },
      // 搜索
      search() {
        this.fetchData({})
      },
      // 编辑
      edit() {
        var list = this.tableChecklist.map((l) => {
          return { csmCode: l.csmCode, csmQuality: l.csmQuality }
        })
        if (list && list.length) {
          this.$refs.edit.open(list)
        } else {
          this.$message.warning('请至少选择一个进行调整')
        }
      },
      // 绑定气瓶
      async binding(row) {
        const res = await customerInfo({ csmCode: row.csmCode })
        console.log(res, 'res')
        await this.$refs.CsmDetailYaJin.open(res.data, 'add')
      // this.$refs.CsmDetailYaJin.open(row)
      },
      // 历史详情
      historyDetail(row) {
        this.$refs.CsmDetailModal.open(row)
      },
      // 审核
      audit() {
        if (!this.tableChecklist.length) {
          this.$message.warning('请选择需要审核的数据')
          return
        }
        if (this.tableChecklist[0].qualityStatus === 2) {
          this.$message.warning('已审核的数据不可重复审核')
          return
        }

        this.$confirm('您确定要执行操作吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.auditSubmit()
          })
          .catch(() => {})
      },
      async auditSubmit() {
        const codes = this.tableChecklist
          .map((v) => {
            return v.csmCode
          })
          .join(',')
        try {
          const res = await queryCustomerLevelAudit({ csmCodes: codes })
          if (res.success) {
            this.fetchData({})
          }
        } catch (e) {
          console.log(e)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  width: 100%;
  padding: 0;
  .content {
    width: 0;
    padding: 0 10px 0 10px;
    flex: 1;
  }
}
</style>
